package vg.com.parse;

import java.io.File;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.androidhive.library.UserFunctions;

import vg.com.chatonline.activity.DashboardActivity;
import vg.com.chatonline.activity.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.SystemClock;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity {

	EditText user, pass;
	Button blogin, register;
	// TextView registrar;
	Httppostaux post;
	linkUrl mUrl;
	JSONParser jparse;
	boolean result_back;
	private ProgressDialog pDialog;
	String id = "";
	String email = "";
	String use_login = "";
	String fullname = "";
	String picture = "";
	ArrayList<Student> arrayList = new ArrayList<Student>();

	// private ArrayList<Student> array;
	private static final String PHRASE = "Item_";
	private String prefBody = "PrefBody";
	private String prefCity = "PrefCity";
	private String prefColor = "PrefColor";
	private String prefDrinker = "PrefDrinker";
	private String prefEducation = "PrefEducation";
	private String prefGender = "PrefGender";
	private String prefMaritalStatus = "PrefMaritalStatus";
	private String prefHeight = "PrefHeight";
	private String prefWeight = "PrefWeight";
	private String prefReligion = "PrefReligion";
	private String prefSmoker = "PrefSmoker";
	private String prefUsertype = "PrefUsertype";

	String body = "/data/data/com.SlideMenu.chatlove/shared_prefs/PrefBody.xml";
	String city = "/data/data/com.SlideMenu.chatlove/shared_prefs/PrefCity.xml";
	String color = "/data/data/com.SlideMenu.chatlove/shared_prefs/PrefColor.xml";
	String Drinker = "/data/data/com.SlideMenu.chatlove/shared_prefs/PrefDrinker.xml";
	String education = "/data/data/com.SlideMenu.chatlove/shared_prefs/PrefEducation.xml";
	String gender = "/data/data/com.SlideMenu.chatlove/shared_prefs/PrefGender.xml";
	String matital = "/data/data/com.SlideMenu.chatlove/shared_prefs/PrefMaritalStatus.xml";
	String height = "/data/data/com.SlideMenu.chatlove/shared_prefs/PrefHeight.xml";
	String weight = "/data/data/com.SlideMenu.chatlove/shared_prefs/PrefWeight.xml";
	String Religion = "/data/data/com.SlideMenu.chatlove/shared_prefs/PrefReligion.xml";
	String smoker = "/data/data/com.SlideMenu.chatlove/shared_prefs/PrefSmoker.xml";
	String Usertype = "/data/data/com.SlideMenu.chatlove/shared_prefs/PrefUsertype.xml";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_ac);
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);
		final File f = new File(body);
		final File f1 = new File(city);
		final File f2 = new File(color);
		final File f3 = new File(Drinker);
		final File f4 = new File(education);
		final File f5 = new File(gender);
		final File f6 = new File(matital);
		final File f7 = new File(height);
		final File f8 = new File(weight);
		final File f9 = new File(Religion);
		final File f10 = new File(smoker);
		final File f11 = new File(Usertype);

		post = new Httppostaux();
		mUrl = new linkUrl();
		user = (EditText) findViewById(R.id.edusuario);
		pass = (EditText) findViewById(R.id.edpassword);
		blogin = (Button) findViewById(R.id.Blogin);

		blogin.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				getWindow()
						.setSoftInputMode(
								WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

				String username = user.getText().toString();
				String password = pass.getText().toString();
				UserFunctions userFunction = new UserFunctions();
				Log.d("Button", "Login");
				JSONObject json = userFunction.loginUser(username, password);

				if (username.equals("") || password.equals("")) {
					Toast.makeText(getApplicationContext(),
							"Vui lÃ²ng Nháº­p ThÃ´ng Tin!", Toast.LENGTH_SHORT)
							.show();
				}

				try {
					String str;
					str = json.getString("susscess");
					Log.d("id:", "" + str);
					
					// Kiem tra du lieu tra ve, neu dung thi thuc hien dang nhap
					if (Integer.parseInt(str) == 1) {
						final ProgressDialog pdRing = ProgressDialog.show(
								Login.this, null, null);
						pdRing.setContentView(R.layout.custom_dialog_login);
						pdRing.setCancelable(true);
						new Thread(new Runnable() {
							public void run() {
								// TODO Auto-generated method stub
								try {
									if (!f.exists()) {
										putPref(prefBody, mUrl.body_type);
									}
									if (!f1.exists()) {
										putPref(prefCity, mUrl.city);
									}
									if (!f2.exists()) {
										putPref(prefColor, mUrl.color);
									}
									if (!f3.exists()) {
										putPref(prefDrinker, mUrl.drinker);
									}
									if (!f4.exists()) {
										putPref(prefEducation, mUrl.education);
									}
									if (!f5.exists()) {
										putPref(prefGender, mUrl.gender);
									}
									if (!f6.exists()) {
										putPref(prefMaritalStatus,
												mUrl.marital_status);
									}
									if (!f7.exists()) {
										putPref(prefHeight, mUrl.my_height);
									}
									if (!f8.exists()) {
										putPref(prefWeight, mUrl.my_weight);
									}
									if (!f9.exists()) {
										putPref(prefReligion, mUrl.religion);
									}
									if (!f10.exists()) {
										putPref(prefSmoker, mUrl.smoker);
									}
									if (!f11.exists()) {
										putPref(prefUsertype, mUrl.user_type);
									}
									Intent i = new Intent(
											getApplicationContext(),
											DashboardActivity.class);
									String use = "tuan".toString();
									i.putExtra("use_id", id);
									i.putExtra("use_login", use);
									i.putExtra("use_fullname", fullname);
									i.putExtra("use_avatar", picture);
									Log.e("ID", id);
									startActivity(i);
									finish();
								} catch (Exception e) {
								}
								pdRing.dismiss();
							}
						}).start();
					}
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			}
		});

		register = (Button) findViewById(R.id.register_login);
		register.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Intent i = new Intent(Login.this, register_1.class);
				// startActivity(i);
			}
		});
	}

	// Dang nhap that bai, rung va thong bao
	public void err_login() {
		Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		vibrator.vibrate(200);
		Toast toast1 = Toast.makeText(getApplicationContext(),
				"Enter Email and password is wrong", Toast.LENGTH_SHORT);
		toast1.show();
	}

	//Kiem tra neu du lieu null
	public boolean checklogindata(String username, String password) {
		if (username.equals("") || password.equals("")) {
			Log.e("Login ui", "checklogindata user or pass error");
			return false;
		} else {
			return true;
		}
	}

	// Luu du lieu tu json, su dung SharedPreferences
	public void putPref(String pref, String url) {
		JSONArray jsa = new JSONArray();
		jparse = new JSONParser();
		jsa = jparse.getJsonarray(url);
		SharedPreferences prefs;
		prefs = getSharedPreferences(pref, MODE_PRIVATE);
		SharedPreferences.Editor editor = prefs.edit();
		for (int i = 0; i < jsa.length(); i++) {
			try {
				editor.putString(PHRASE + i + "", jsa.getString(i));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		editor.commit();
	}
}
